<?php
/**
 * Author: Traveler
 * Time  : 2021/9/4 19:17
 */

namespace app\service;


use app\ErrorCode;
use app\model\DepartmentModel;
use sunshine\basic\RestService;
use sunshine\exceptions\ApiException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class DepartmentService extends RestService
{
    /**
     * DepartmentService constructor.
     */
    public function __construct()
    {
        $this->model = new DepartmentModel();
        $this->initialize();
    }

    /**
     * 初始化
     */
    public function initialize()
    {
    }

    /**
     * 删除部门(重写)
     *
     * @param int        $id 部门id
     * @param array|null $relation
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delete(int $id, ?array $relation = null): bool
    {
        // 检查部门是否在使用中
        $staffService = new StaffService();
        if ($staffService->getCountByDepartment($id) > 0) {
            throw new ApiException(ErrorCode::DEPARTMENT_USING);
        }

        return parent::delete($id);
    }
}